﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Milestone.Boot.Indexes;
using Milestone.ComponentModel;
using Milestone.Model.Parties;
using Raven.Client;
using Raven.Client.Linq;
using Topics.Radical.Observers;
using Topics.Radical.Windows.Behaviors;

namespace Milestone.Presentation.Tasks
{
	class AddNewExecutedTask : AbstractUserTask
	{
		readonly IDocumentStore store;

		public AddNewExecutedTask( IDocumentStore store )
		{
			this.store = store;

			this.Data = new ObservableCollection<Parties_FullTextSearchIndex.PartySimpleView>();

			PropertyObserver.For( this )
				.Observe( v => v.UserText, ( v, s ) =>
				{
					if( this.UserText.Length < 3 )
					{
						this.Data.Clear();
					}
					else if( this.UserText.Length >= 3 )
					{
						this.Data.Clear();
						using( var session = this.store.OpenSession() )
						{
							var results = session.Query<Parties_FullTextSearchIndex.PartySimpleView, Parties_FullTextSearchIndex>()
								.Where( view => view.DisplayName.StartsWith( this.UserText ) )
								.AsProjection<Parties_FullTextSearchIndex.PartySimpleView>();

							foreach( var item in results )
							{
								this.Data.Add( item );
							}
						}
					}
				} );
		}

		public override string DisplayName
		{
			get { return "Add new report entry."; }
		}

		public String UserText
		{
			get { return this.GetPropertyValue( () => this.UserText ); }
			set { this.SetPropertyValue( () => this.UserText, value ); }
		}

		public ObservableCollection<Parties_FullTextSearchIndex.PartySimpleView> Data { get; private set; }

		public Parties_FullTextSearchIndex.PartySimpleView Choosen
		{
			get { return this.GetPropertyValue( () => this.Choosen ); }
			set { this.SetPropertyValue( () => this.Choosen, value ); }
		}

		public override void Execute()
		{
			
		}
	}
}
